//
//  AppDelegate.m
//  yigou
//
//  Created by wangdianlei on 2017/1/4.
//  Copyright © 2017年 hanyiwang. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarControllerConfig.h"
#import "TabBarPublishButton.h"
#import "IndexViewController.h"
#import "DyShare.h"
#import "WeiboUser.h"
#import <IQKeyboardManager.h>
#import "GCQiniuUploadManager.h"
#import "MMLauchImage.h"
#import "WSMovieController.h"
#import "IntroScrollViewController.h"
#import "JKNotifier.h"

@interface AppDelegate () <WXApiDelegate, WeiboSDKDelegate, IntroViewDelegate, EMChatManagerDelegate>

@property (strong, nonatomic) IntroScrollViewController *intro;
@property (strong, nonatomic) UIView *mediaView;
@property (strong, nonatomic) WSMovieController *wsCtrl;

@end

@implementation AppDelegate

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSGVIDEOPLAYEND object:nil];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
//    EMOptions *options = [EMOptions optionsWithAppkey:HXKEY];
//    options.apnsCertName = @"iosyigou";
//    [[EMClient sharedClient] initializeSDKWithOptions:options];
    //wanyihuidev  wanyihuidis
    NSString *apnsCertName = nil;
#if DEBUG
    apnsCertName = @"wanyihuidev";
#else
    apnsCertName = @"wanyihuidis";
#endif
    [[EaseSDKHelper shareHelper] hyphenateApplication:application
                        didFinishLaunchingWithOptions:launchOptions
                                               appkey:HXKEY
                                         apnsCertName:apnsCertName
                                          otherConfig:@{kSDKConfigEnableConsoleLogger:[NSNumber numberWithBool:YES]}];
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
    
    [[DyShare getInstance] registerQQWithAppId:QQKEY];
    [[DyShare getInstance] registerWeiboWithAppId:WBKEY];
    [[DyShare getInstance] registerWeiXinWithAppId:WXKEY description:@"玩艺汇"];
    [self registerQiNiuToken];
    [MobStatHelper setup];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [TabBarPublishButton registerPlusButton];
    BaseTabBarControllerConfig *tabBarControllerConfig = [[BaseTabBarControllerConfig alloc] init];
    [self.window setRootViewController:tabBarControllerConfig.tabBarController];
    [self.window makeKeyAndVisible];
    [self loadKeyboardManager];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    [IQKeyboardManager sharedManager].enable = NO;
    [self versionCheck];
    [self launchImageCheck];
    
    //iOS8以上 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        [application registerForRemoteNotifications];
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge |
        UIUserNotificationTypeSound |
        UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:nil];
        [application registerUserNotificationSettings:settings];
    }
    else{
        UIRemoteNotificationType notificationTypes = UIRemoteNotificationTypeBadge |
        UIRemoteNotificationTypeSound |
        UIRemoteNotificationTypeAlert;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:notificationTypes];
    }
    
    return YES;
}

- (void)registerQiNiuToken {
    [[GCQiniuUploadManager sharedInstance] registerWithScope:QNSCOPE
                                                   accessKey:QNACCESS
                                                   secretKey:QNSECRET];
    [[GCQiniuUploadManager sharedInstance] createToken];
}

- (void)playEnd:(NSNotification *)notify {
    if (self.mediaView) {
        [self.mediaView removeFromSuperview];
//        self.intro = [[IntroScrollViewController alloc] initWithNibName:@"IntroScrollViewController" bundle:nil];
//        self.intro.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
//        self.intro.delegate = self;
//        [self.window addSubview:self.intro.view];
    }
}

- (void)versionCheck {
    if ([[UserData preVersion] compare:VERSION] == NSOrderedAscending) {
        [[TMCache sharedCache] removeAllObjects];
        [UserData setPreVersion:VERSION];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playEnd:) name:MSGVIDEOPLAYEND object:nil];
        DYLog(@"current version:%@", VERSION);
        self.mediaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
        [self.window addSubview:self.mediaView];
        
        self.wsCtrl = [[WSMovieController alloc]init];
        self.wsCtrl.movieURL = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"qidong"ofType:@"mp4"]];
        self.wsCtrl.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        [self.mediaView addSubview:self.wsCtrl.view];
    }
}

- (void)beginApp {
    [UIView animateWithDuration:0.8 animations:^ {
        self.intro.view.alpha = 0;
    } completion:^(BOOL finished) {
        [self.intro.view removeFromSuperview];
        self.intro = nil;
    }];
}

- (void)launchImageCheck {
    DYBaseRequest *request = [DYBaseRequest new];
    NSString *url = [NSString stringWithFormat:@"%@/sys/login/indexAd?size=%d", APIYIGOU, 1];
    request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *dict = [NSDictionary changeType:request.responseJSONObject];
        DYLog(@"dict:%@", dict.description);
        NSArray *enable = [[dict valueForKey:@"data"] valueForKey:@"ad_img_url"];
        if (enable.count > 0) {
            NSError *error = nil;
            [UserData setShouldShowLauchImage:YES];
            MMLauchImage *launchInfo = [[TMCache sharedCache] objectForKey:MMLAUCH_IMAGE];
            //compare with before
            if (launchInfo != nil) {
                if (![launchInfo.ad_img_url[0] isEqualToString:enable[0]]) {
                    [UserData setLauchImageHasDownload:NO];
                    [self downloadLaunchImage:enable[0]];
                }
            } else {//first download lauchimage
                [UserData setLauchImageHasDownload:NO];
                [self downloadLaunchImage:enable[0]];
            }
            
            //save launch info
            MMLauchImage *mmLaunch = [[MMLauchImage alloc] initWithDictionary:[dict valueForKey:@"data"] error:&error];
            [[TMCache sharedCache] setObject:mmLaunch forKey:MMLAUCH_IMAGE];
        } else {
            [UserData setShouldShowLauchImage:NO];
            [UserData setLauchImageHasDownload:NO];
        }
    } error:^(YTKBaseRequest *request) {
    } failure:^(YTKBaseRequest *request) {
    }];
}

- (void)downloadLaunchImage:(NSString *)url {
    //download new startpage
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:url] options:SDWebImageDownloaderLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
        [UserData setLauchImageHasDownload:YES];
        [[SDImageCache sharedImageCache] storeImage:image forKey:@"deyistartpage" toDisk:YES];
    }];
}

- (void)loadKeyboardManager
{
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    //    控制整个功能是否启用。
    manager.enable = YES;
    manager.overrideKeyboardAppearance = YES;
    //控制点击背景是否收起键盘
    manager.shouldResignOnTouchOutside = YES;
    //    //控制键盘上的工具条文字颜色是否用户自定义。  注意这个颜色是指textfile的tintcolor
    //    manager.shouldToolbarUsesTextFieldTintColor = YES;
    //    //中间位置是否显示占位文字(默认是YES)
    //    manager.shouldShowTextFieldPlaceholder = YES;
    //    //设置占位文字的字体大小
    manager.placeholderFont = [UIFont boldSystemFontOfSize:18];
    //控制是否显示键盘上的工具条。
    manager.enableAutoToolbar = NO;
    //某个类中禁止使用工具条
    //    [[IQKeyboardManager sharedManager]disableToolbarInViewControllerClass:[UIViewController class]];

}

- (void)messagesDidReceive:(NSArray *)aMessages {
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateBackground) {
        UILocalNotification *notification = [[UILocalNotification alloc]init];
        //设置调用时间
        notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.0];//通知触发时间，10s之后
        //notification.repeatInterval = 2; //通知重复次数
        
        //设置通知属性
        notification.alertBody = @"您收到一条消息";//通知主体
        notification.applicationIconBadgeNumber = 1;//应用程序右上角显示的未读消息数
        notification.alertAction = @"您收到一条消息";//待机界面的滑动动作提示
        notification.alertLaunchImage = @"Default";//通过点击通知打开应用时的启动图片，这里使用程序启动图片
        //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音，默认消息声音
        //notification.soundName=@"msg.caf";//通知声音（需要真机才能听到声音）
        
        //设置用户信息
        //notification.userInfo = @{@"id":@1,@"user":@"XF"};
        
        //调用通知
        [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    } else if (state == UIApplicationStateActive) {
        [JKNotifier showNotifer:@"您收到一条消息"];
        [JKNotifier handleClickAction:^(NSString *name, NSString *detail, JKNotifier *notifier) {
            AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
            CYLTabBarController *mvc = (CYLTabBarController *)appDelegate.window.rootViewController;
            UINavigationController *viewController = (UINavigationController *)mvc.selectedViewController;
            EaseConversationListViewController *chatController = [[EaseConversationListViewController alloc] init];
            [viewController pushViewController:chatController animated:YES];
        }];
    }
}

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    CYLTabBarController *mvc = (CYLTabBarController *)appDelegate.window.rootViewController;
    UINavigationController *viewController = (UINavigationController *)mvc.selectedViewController;
    EaseConversationListViewController *chatController = [[EaseConversationListViewController alloc] init];
    [viewController pushViewController:chatController animated:YES];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    CYLTabBarController *mvc = (CYLTabBarController *)appDelegate.window.rootViewController;
    UINavigationController *viewController = (UINavigationController *)mvc.selectedViewController;
    EaseConversationListViewController *chatController = [[EaseConversationListViewController alloc] init];
    [viewController pushViewController:chatController animated:YES];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    completionHandler(UIBackgroundFetchResultNewData);
    AppDelegate* appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    CYLTabBarController *mvc = (CYLTabBarController *)appDelegate.window.rootViewController;
    UINavigationController *viewController = (UINavigationController *)mvc.selectedViewController;
    EaseConversationListViewController *chatController = [[EaseConversationListViewController alloc] init];
    [viewController pushViewController:chatController animated:YES];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    [[EMClient sharedClient] bindDeviceToken:deviceToken];
}

// 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"error -- %@",error);
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    [UserData setShowLaunchTime:[TimeHelper currentTimeStamp]];
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [[NSNotificationCenter defaultCenter] postNotificationName:MSGSHOWLAUNCHIMG object:nil];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    [TencentOAuth HandleOpenURL:url];
    //[WeiboSDK handleOpenURL:url delegate:[DyShare getInstance]];
    [WeiboSDK handleOpenURL:url delegate:self];
    [WXApi handleOpenURL:url delegate:self];
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    NSLog(@"%@",url);
    NSString *urlStr=[[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *wxORwb = [urlStr substringToIndex:2];
    NSLog(@"%@",wxORwb);
    if ([wxORwb isEqualToString:@"wb"]) {
        return [WeiboSDK handleOpenURL:url delegate:self];
    }
    else if ([wxORwb isEqualToString:@"wx"]){
        BOOL isSuc = [WXApi handleOpenURL:url delegate:self];
        return  isSuc;
    } else {
        [TencentOAuth HandleOpenURL:url];
        return YES;
    }
}

- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[SendAuthResp class]]) {//登陆
        SendAuthResp *authResp = (SendAuthResp *)resp;
        //NSString *strTitle = [NSString stringWithFormat:@"Auth结果"];
        NSString *strMsg = [NSString stringWithFormat:@"code:%@,state:%@,errcode:%d", authResp.code, authResp.state, authResp.errCode];
        DYLog(@"strMsg%@", strMsg);
        
        if (resp.errCode == 0) {
            NSString *wxurl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code", WXKEY, WXSECRET, authResp.code];
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSURL *zoneUrl = [NSURL URLWithString:wxurl];
                NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
                NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (data) {
                        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                        //DYLog(@"dict%@", dic);
                        [DataCenter sharedDataCenter].wxtoken = [dic objectForKey:@"access_token"];
                        [DataCenter sharedDataCenter].wxopenid = [dic objectForKey:@"openid"];
                        [DataCenter sharedDataCenter].wxunionid = [dic objectForKey:@"unionid"];
                        [self requestUserInfoByToken:[DataCenter sharedDataCenter].wxtoken andOpenid:[DataCenter sharedDataCenter].wxopenid = [dic objectForKey:@"openid"]];
                    }
                });
            });
        } else {
            [ViewFactory showErrorStrMsg:@"登陆失败!"];
        }
    } else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {//分享
        SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
        NSString *str = [NSString stringWithFormat:@"%d",sendResp.errCode];
            if (sendResp.errCode == WXSuccess) {
                [ViewFactory showSuccess:@"分享成功！"];
            }
    } else {//支付
        NSLog(@"errCode:%d,errString:%@,type:%d",resp.errCode,resp.errStr,resp.type);
        if (resp.errCode == 0) {
            //成功
//            [[NSNotificationCenter defaultCenter] postNotificationName:KEY_paySucces object:nil];
            [ViewFactory showSuccess:@"支付成功！"];
        } else{
            //[[NSNotificationCenter defaultCenter] postNotificationName:@"buyError" object:nil];
            [ViewFactory showInfoMsg:@"支付未完成"];
        }
    }
}

-(void)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"dic  ==== %@",dict);
        [DataCenter sharedDataCenter].nickname = [dict objectForKey:@"nickname"];
        [DataCenter sharedDataCenter].headurl = [dict objectForKey:@"headimgurl"];
        [self wxLogin];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error %ld",(long)error.code);
    }];
}

- (void)wxLogin {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:THIRDLOGIN parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].nickname dataUsingEncoding:NSUTF8StringEncoding] name:@"nick_name"];
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].headurl dataUsingEncoding:NSUTF8StringEncoding] name:@"head_url"];
        [formData appendPartWithFormData:[@"01" dataUsingEncoding:NSUTF8StringEncoding] name:@"register_type"];
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].wxopenid dataUsingEncoding:NSUTF8StringEncoding] name:@"openid"];
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].wxunionid dataUsingEncoding:NSUTF8StringEncoding] name:@"unionid"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
        if ([[dict valueForKey:@"code"] intValue] == 100) {
            [UserData login:[dict objectForKey:@"data"]];
            [ViewFactory showSuccess:@"登录成功！"];
            [[NSNotificationCenter defaultCenter] postNotificationName:POST_THIRDLOGIN object:nil];
            NSLog(@"dic  ==== %@",dict);
        } else {
            [ViewFactory showErrorStrMsg:@"登录失败！"];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error %ld",(long)error.code);
        [ViewFactory showErrorStrMsg:@"登录失败！"];
    }];
    
//    NSDictionary *parameters = @{ @"nick_name" : [DataCenter sharedDataCenter].nickname,
//                                  @"head_url" : [DataCenter sharedDataCenter].headurl,
//                                  @"openid" : [DataCenter sharedDataCenter].wxopenid,
//                                  @"register_type" : @"01",
//                                  @"unionid" : [DataCenter sharedDataCenter].wxunionid};
//    [manager POST:THIRDLOGIN parameters:parameters success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSDictionary *dict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"dic  ==== %@",dict);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"error %ld",(long)error.code);
//    }];
    
//    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *urlStr = [NSString stringWithFormat:@"%@/sys/login/memberOtherLogin?nick_name=%@&head_url=%@&openid=%@&register_type=%@&unionid=%@",APIYIGOU, [DataCenter sharedDataCenter].nickname, [[DataCenter sharedDataCenter].headurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [DataCenter sharedDataCenter].wxopenid, @"01", [DataCenter sharedDataCenter].wxunionid];
//    request.requestUrl = urlStr;
////    request.requestPostDic = @{ @"nick_name" : @"test",
////                                @"head_url" : [DataCenter sharedDataCenter].headurl,
////                                @"openid" : [DataCenter sharedDataCenter].wxopenid,
////                                @"register_type" : @"01",
////                                @"unionid" : [DataCenter sharedDataCenter].wxunionid};
//    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
//        [UserData login:[allDic objectForKey:@"data"]];
//    } error:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:@"登录失败！"];
//    } failure:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:NETWORK_ERR];
//    }];
}

#pragma mark -- WeiboSDKDelegate
- (void)didReceiveWeiboResponse:(WBBaseResponse *)response {
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        if (response.statusCode == 0) {
            [ViewFactory showSuccess:@"分享成功！"];
        }
        else {
            //[ViewFactory showErrorStrMsg:@"分享失败！"];
        }
    } else if ([response isKindOfClass:WBAuthorizeResponse.class]){
        if (response.statusCode == 0) {
            NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.userId: %@\nresponse.accessToken: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken],  NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
            [DataCenter sharedDataCenter].wxopenid = [(WBAuthorizeResponse *)response userID];
            [DataCenter sharedDataCenter].nickname = @"";
            [DataCenter sharedDataCenter].headurl = @"";
            [DataCenter sharedDataCenter].wxtoken = [(WBAuthorizeResponse *)response accessToken];
            
            [WBHttpRequest requestForUserProfile:[(WBAuthorizeResponse *)response userID] withAccessToken:[DataCenter sharedDataCenter].wxtoken andOtherProperties:nil queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
                
                NSString *title = nil;
                UIAlertView *alert = nil;
                if (error) {
                    title = NSLocalizedString(@"请求异常", nil);
                    alert = [[UIAlertView alloc] initWithTitle:title
                                                       message:[NSString stringWithFormat:@"%@",error]
                                                      delegate:nil
                                             cancelButtonTitle:NSLocalizedString(@"确定", nil)
                                             otherButtonTitles:nil];
                } else {
                    WeiboUser *dict = result;
                    [DataCenter sharedDataCenter].nickname = dict.screenName;
                    [DataCenter sharedDataCenter].headurl = dict.avatarLargeUrl;
                    [self wbLogin];
                }
            }];
        }
        else {
            [ViewFactory showErrorStrMsg:@"新浪微博登录失败！"];
        }
    }
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request {
    
}

- (void)wbLogin {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:THIRDLOGIN parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].nickname dataUsingEncoding:NSUTF8StringEncoding] name:@"nick_name"];
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].headurl dataUsingEncoding:NSUTF8StringEncoding] name:@"head_url"];
        [formData appendPartWithFormData:[@"02" dataUsingEncoding:NSUTF8StringEncoding] name:@"register_type"];
        [formData appendPartWithFormData:[[DataCenter sharedDataCenter].wxopenid dataUsingEncoding:NSUTF8StringEncoding] name:@"openid"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        NSDictionary *dict = [NSDictionary changeType:(NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]];
        if ([[dict valueForKey:@"code"] intValue] == 100) {
            [UserData login:[dict objectForKey:@"data"]];
            [ViewFactory showSuccess:@"登录成功！"];
            [[NSNotificationCenter defaultCenter] postNotificationName:POST_THIRDLOGIN object:nil];
            NSLog(@"dic  ==== %@",dict);
        } else {
            [ViewFactory showErrorStrMsg:@"登录失败！"];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error %ld",(long)error.code);
        [ViewFactory showErrorStrMsg:@"登录失败！"];
    }];
}

@end
